package com.github.binarylei.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author: leigang
 * @version: 2018-04-05
 */
public class ZookeeperBase {

    /** zookeeper 地址，多个用 ; 隔开 */
    static final String CONNECT_ADDR = "127.0.0.1";
    /** session 超时时间，单位：ms */
    static final int SESSION_OUTTIME = 5000;
    /** 阻塞程序执行，用于等待zookeeper 连接成功，发送成功信号 */
    static final CountDownLatch connectedSemaphore = new CountDownLatch(1);
    
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZooKeeper zooKeeper = new ZooKeeper(CONNECT_ADDR, SESSION_OUTTIME, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                // 获取事件的状态
                Event.KeeperState state = event.getState();
                Event.EventType type = event.getType();
                // 如果是建立连接
                if (state == Event.KeeperState.SyncConnected) {
                    if (type == Event.EventType.None) {
                        // 如果连接建立成功，则发送信号，让后续阻塞程序向下执行
                        connectedSemaphore.countDown();
                        System.out.println("zookeeper 连接建立");
                    }
                }

            }
        });

        // 进行阻塞
        connectedSemaphore.await();
        System.out.println("============================");

        //1. 创建节点
        zooKeeper.create(
                "/testRoot",            // 节点路径，不允许递归创建节点
                "testRoot".getBytes(),        // 节点内容
                ZooDefs.Ids.OPEN_ACL_UNSAFE,  // 节点权限，一般情况下不用关注
                CreateMode.PERSISTENT);       // 节点类型

        //2. 获取节点
        Stat stat = new Stat();
        byte[] data = zooKeeper.getData("/testRoot", false, stat);
        System.out.println("获取节点：" + new String(data));

        //3. 获取子节点
        List<String> nodes = zooKeeper.getChildren("/", false);
        for (String node : nodes) {
            System.out.println("获取" + node + "子节点：" +
                    new String(zooKeeper.getData("/" + node, false, null)));
        }

        //4. 修改节点的值
        stat = zooKeeper.setData("/testRoot", "111".getBytes(), stat.getVersion());

        //5. 判断节点是否存在
        System.out.println("节点是否存在：" + zooKeeper.exists("/testRoot", false));

        //6. 删除节点，不支持递归删除
        zooKeeper.delete("/testRoot", stat.getVersion(), new AsyncCallback.VoidCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx) {
                System.out.println("响应码：" + rc);
                System.out.println("路径：" + path);
                System.out.println("上下文：" + ctx);
            }
        }, 1);

        zooKeeper.close();
    }
}
